<template>
  <view>
    <view class="douyin-btn">
      <slot name="button">
        <u-button
          type="primary"
          color="#b8f19a"
          :custom-style="btnStyle"
          :text="text"
          @tap="getMpUserInfo"
        ></u-button>
      </slot>
    </view>
    <maya-popup
      :show.sync="bindingShow"
      title="绑定手机号码"
    >
      <view class="binding-content">
        <u-form
          ref="uForm"
          label-position="top"
          :model="form"
          :rules="rules"
        >
          <u-form-item prop="form.mobile">
            <u-input
              v-model="form.mobile"
              :placeholder-style="placeholderStyle"
              placeholder="请输入手机号"
              focus
              shape="circle"
              border="none"
              type="number"
              :custom-style="inputStyle"
              maxlength="11"
            />
          </u-form-item>
          <u-form-item prop="form.code">
            <u-input
              v-model="form.code"
              :placeholder-style="placeholderStyle"
              placeholder="请输入验证码"
              shape="circle"
              border="none"
              type="number"
              :custom-style="inputStyle"
              maxlength="6"
            >
              <template slot="suffix">
                <u-code
                  ref="uCode"
                  change-text="X秒重新获取"
                  @change="codeChange"
                ></u-code>
                <u-link
                  :text="tips"
                  size="mini"
                  color="#333333"
                  @click="getCode"
                ></u-link>
              </template>
            </u-input>
          </u-form-item>
          <u-form-item>
            <u-button
              type="primary"
              color="#73EA46"
              :custom-style="bindBtnStyle"
              text="绑定手机号"
              @click="loginChange"
            ></u-button>
          </u-form-item>
        </u-form>
      </view>
    </maya-popup>
  </view>
</template>

<script>
import { loginByMp, sendMobile } from '@/api/common.js';
import mayaPopup from './maya-popup.vue';
import { mapMutations, mapActions, mapGetters } from 'vuex';
const btnStyle = {
  width: '100%',
  height: '54px',
  borderRadius: '30px',
  color: '#2B2B2B',
};
export default {
  components: {
    mayaPopup,
  },
  props: {
    btnStyle: {
      type: Object,
      default: () => {
        return btnStyle;
      },
    },
    text: {
      type: String,
      default: '抖音一键登录',
    },
  },
  computed: {
    ...mapGetters(['isLogin']),
  },
  data() {
    return {
      form: {
        mobile: '', // 手机号码
        code: '', // 验证码
        tiktokCode: '', // 如果小程序用户登录下会返回
        AVATAR: '',
        NICKNAME: '',
        SEX: '',
      },
      bindingShow: false, // 绑定手机号码弹窗
      placeholderStyle: 'font-size: 28rpx;line-height: 108rpx;color: #999999;',
      inputStyle: Object.freeze({
        backgroundColor: '#eee',
        borderColor: '#eee',
        height: '54px',
        padding: '0 20px',
      }),
      tips: '',
      bindBtnStyle: btnStyle,
      rules: {},
    };
  },
  mounted() {},
  methods: {
    ...mapMutations(['setToken']),
    ...mapActions(['getUserInfo']),
    // 小程序登录
    mpLogin(isLogin = true) {
      const that = this;
      uni.login({
        force: true,
        success({ code }) {
          that.form.tiktokCode = code;
          console.log('获取mpLogin');
          if (isLogin) {
            that.loginChange();
          }
        },
        fail(e) {
          throw new Error(e);
        },
      });
    },

    // 发起登录申请
    async loginChange() {
      try {
        // 如果已经获取过用户信息了，则直接进行登录
        if (!this.form.NICKNAME) {
          this.getMpUserInfo();
          return false;
        }
        if (!this.form.tiktokCode) {
          this.mpLogin();
          return;
        }
        uni.showLoading({
          title: '登录中...',
        });
        const data = await loginByMp(this.form);
        this.bindingShow = false;
        this.resetForm();
        this.setToken(data.access_token);
        await this.getUserInfo();
        uni.hideLoading();
      } catch (e) {
        //TODO handle the exception
        if (e.data && e.data.code === 1030) {
          // 未绑定定手机号码
          this.bindingShow = true;
        }
        this.form.tiktokCode = '';
        throw new Error(e);
      }
    },
    // 验证码状态变更
    codeChange(text) {
      this.tips = text;
    },
    resetForm() {
      this.form = {
        mobile: '', // 手机号码
        code: '', // 验证码
        tiktokCode: '', // 如果小程序用户登录下会返回
        AVATAR: '',
        NICKNAME: '',
        SEX: '',
      };
    },
    // 获取验证码
    async getCode() {
      try {
        if (this.$refs.uCode.canGetCode) {
          if (!this.form.mobile) {
            uni.$u.toast('请填写正确手机号');
            return false;
          }
          // 模拟向后端请求验证码
          uni.showLoading({
            title: '正在获取验证码',
          });
          await sendMobile(this.form.mobile);
          uni.hideLoading();
          uni.$u.toast('验证码已发送');
          this.$refs.uCode.start();
        } else {
          uni.$u.toast('倒计时结束后再发送');
        }
      } catch (e) {
        uni.hideLoading();
        throw new Error(e);
      }
    },
    end() {
      uni.$u.toast('倒计时结束');
    },
    start() {
      uni.$u.toast('倒计时开始');
    },
    // 授权获取用户信息
    async getMpUserInfo() {
      if (this.isLogin) {
        return false;
      }
      const that = this;
      uni.getUserProfile({
        force: true,
        success({ userInfo }) {
          that.form.AVATAR = userInfo.avatarUrl;
          that.form.NICKNAME = userInfo.nickName;
          that.form.SEX = userInfo.gender === 0 ? 'female' : 'male';
          that.mpLogin(true);
        },
        fail(e) {
          uni.showToast({
            title: '用户信息获取失败!',
          });
          throw new Error(e);
        },
      });
    },
  },
};
</script>

<style lang="scss">
.binding-content {
  padding: 20rpx 0 232rpx;
  width: 85%;
  margin: 0 auto;
}
.douyin-btn {
  width: 315px;
  margin: 0 auto;
}
</style>
